package triangle;

/**
 * This file is part of Rodney Ryan's submission of
 * his solution to the "Triangle Puzzle".
 *
 * This class calculates the maximal value of a
 * triangle.
 *
 * rodney@rodneyryan.com
 */
public class TriangleMaximalCalculator {

    public TriangleMaximalCalculator() {
        super();
    }

    public long calculate(Triangle triangle) {
        int numberOfRows = triangle.getNumberOfRows();
        if (numberOfRows == 0) {
            return 0;

        } else if (numberOfRows == 1) {
            long[] row = new long[1];
            triangle.loadRow(row);
            return row[0];
        }

        long[] bottomRow = new long[numberOfRows];
        long[] topRow = new long[bottomRow.length - 1];

        int length = topRow.length;

        triangle.loadRow(bottomRow);
        triangle.loadRow(topRow);

        while (length > 0) {
            for (int cell = 0; cell < length; cell++) {
                topRow[cell] += Math.max(bottomRow[cell], bottomRow[cell + 1]);
            }

            System.arraycopy(topRow, 0, bottomRow, 0, length);
            length = triangle.loadRow(topRow);
        }

        return topRow[0];
    }
}
